<template>
	<view class="main">
		<scroll-view class="navscroll" scroll-x="true">
			<view class="item" 
			:class="navIndex==item.id? 'active' : '' " 
			v-for="(item,index) in navArr"
			:key="item.id"
			@click="handler(item.id)"
			>
			{{item.classname}}
			</view>
		</scroll-view>
		<view class="content">
			<view class="row" v-for="item in newsArr">
				<!-- 自定义组件默认引入 -->
				<Newsbox :newsObj="item"></Newsbox>
			</view>
		</view>
		<!-- 当请求无数据时显示默认图片 -->
		<view class="defaultPic" v-if="!newsArr.length">
			<image src="../../static/images/nodata.png"></image>
		</view>
		<!-- 下拉时显示数据正在加载或者已经加载完成的状态 -->
		<view class="loadInfo">
			<view v-if="loading==1">Loading...</view>
			<view v-if="loading==2">No More Info</view>
		</view>
	</view>
</template>
<script>

	export default {
		data() {
			return {
				// 用户在导航栏点击了哪个item，
				// 作用：实现导航栏点击目标高亮显示的效果，拿到点击对应的id作为发送请求的参数
				navIndex:0,
				navArr:[],
				newsArr:[],
				// loading:1表示正在加载，2表示数据已经加载完成
				loading:0,
				// 请求的页数
				currentNewsPage:1,
				// 每次请求放回的新闻数据
				new_newsArr:[],
			}
		},
		onLoad() {
			this.getNavData();
			this.handler(50);
		},
		onReachBottom(){
			if(this.loading==2)return;
			this.getNewsData();
		},
		// onPulldownRefresh下拉刷新事件，onRreshBottom触底事件
		methods: {
			handler(id){
				// 初始化
				this.newsArr=[];
				this.loading=0;
				this.currentNewsPage=1;
				// 把当前点击导航栏的对应的id，
				this.navIndex=id;
				this.getNewsData();
			},
			getNavData(){
				uni.request({
					url:"https://tea.qingnian8.com/api/qingnews/category",
					header:{
						"access-key":"123abc321"
					},
					success:res=>{
						this.navArr=res.data.data;
					}
				})
			},
			getNewsData(){
				this.loading=1;
					uni.request({
						url:"https://tea.qingnian8.com/api/qingnews/newslist",
						data:{
							cid:`${this.navIndex}`,
							page:`${this.currentNewsPage}`,
						},
						header:{
							"access-key":"123abc321"
						},
						success:res=>{
							console.log('getNewsData');
							console.log(res.data);
							if(!res.data.data.length){
								this.loading=2;
								return;
							}
							this.new_newsArr=res.data.data
							this.newsArr=[...this.newsArr,...this.new_newsArr];
						}
					})
				this.loading=0;
				this.currentNewsPage++;
			}
		}
	}
</script>

<style lang="scss" scoped>
.navscroll{
	height: 100rpx;
	background: #F7F8FA;
	// white-space属性？
	white-space: nowrap;
	position: fixed;
	.item{
		font-size: 40rpx;
		display: inline-block;
		line-height: 100rpx;
		padding: 0 25rpx;
		&.active{
			color:#31c27c;
		}
	}
}
.content{
	padding: 25rpx;
	padding-top: 125rpx;
	.row{
		padding: 20rpx 0;
		border-bottom: 1rpx #999 dotted;
	}
}
.defaultPic{
	display: flex;
	justify-content: center;
	align-items: center;
	image{}	
}
.loadInfo{
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 30rpx 0;
}
</style>
